var QualityAssurances = {//质量管理管理初始化
    id: "QualityAssurancesOneTable",	//表格id
    seItem: null,		//选中的条目
    table: null,
    layerIndex: -1
};

function _cellStyles(value, row, index) {
    if (row.scoringStatus == 1) {
        return {
            css: {
                "background-color": "#d1cac3",
                "overflow": "hidden",
                "white-space": "nowrap",
                "text-overflow": "ellipsis"
            }
        }
    } else {
        return {css: {"overflow": "hidden", "white-space": "nowrap", "text-overflow": "ellipsis"}}
    }
};

QualityAssurances.initColumn = function () {//初始化表格的列
    return [
        {title: '', field: 'selectItem', visible: false,},
        {
            title: '<input id="checkAll" name="checkImgNum" type="checkbox">',
            field: 'num',
            align: 'center',
            valign: 'middle',
            width: 40,
            formatter: function (value, row, index) {
                return '<input id="' + value + '" name="checkImgNum" type="checkbox">'
            },
        },
        {title: 'customerId', field: 'customerId', visible: false, align: 'center', valign: 'middle'},
        {title: 'scoringStatus', field: 'scoringStatus', visible: false, align: 'center', valign: 'middle'},
        {title: 'iconName1', field: 'iconName1', visible: false, align: 'center', valign: 'middle'},
        {title: 'recordCheck', field: 'recordCheck', visible: false, align: 'center', valign: 'middle'},
        {title: 'id', field: 'id', visible: false, align: 'center', valign: 'middle'},
        {title: 'photoType', field: 'photoType', visible: false, align: 'center', valign: 'middle'},
        {title: 'standardScore', field: 'standardScore', visible: false, align: 'center', valign: 'middle'},
        {title: 'scoreTOTALb', field: 'scoreTOTALb', visible: false, align: 'center', valign: 'middle'},
        {title: 'scoreb', field: 'scoreb', visible: false, align: 'center', valign: 'middle'},
        {
            title: '上传时间', field: 'addTime', align: 'center', valign: 'middle', sortable: true, width: 100,
            formatter: function (value, row, index) {
                if (value != null && value != "" && value != undefined) {
                    return '<div>'+value.substring(0,10)+'</div>' +
                        '<div>'+value.substring(11,19)+'</div>'
                }
            },
            cellStyle: function (value, row, index) {
                return _cellStyles(value, row, index);
            }
        },
        {
            title: '患者姓名', field: 'customerName', align: 'center', valign: 'middle', width: 90,
            cellStyle: function (value, row, index) {
                return _cellStyles(value, row, index);
            }
        },
        {
            title: '患者电话', field: 'customerPhone', align: 'center', valign: 'middle', width: 120,
            cellStyle: function (value, row, index) {
                return _cellStyles(value, row, index);
            }
        },
        {
            title: '上传人', field: 'addName', align: 'center', valign: 'middle', width: 80,
            cellStyle: function (value, row, index) {
                return _cellStyles(value, row, index);
            }
        },
        {
            title: '备注', field: 'remarks', align: 'center', valign: 'middle', width: 80,
            cellStyle: function (value, row, index) {
                return _cellStyles(value, row, index);
            }
        },
        {
            title: '门诊', field: 'outpatientName', align: 'center', valign: 'middle', width: 80,
            cellStyle: function (value, row, index) {
                return _cellStyles(value, row, index);
            }
        },
        {
            title: '牙位', field: 'toothPosition', align: 'center', valign: 'middle', width: 60,
            cellStyle: function (value, row, index) {
                return _cellStyles(value, row, index);
            }
        },
        {
            title: '医生', field: 'doctor', align: 'center', valign: 'middle', width: 80,
            cellStyle: function (value, row, index) {
                return _cellStyles(value, row, index);
            }
        },
        {
            title: '类型', field: 'iconName', align: 'center', valign: 'middle', width: 70,
            cellStyle: function (value, row, index) {
                return _cellStyles(value, row, index);
            }
        },
        {
            title: '图片', field: 'imageUrl', align: 'center', valign: 'middle', width: 120,
            formatter: function (value, row, index) {
                return "<a href='javascript:void(0)' data-magnify='gallery' data-group='g1' data-src='"+value+"'><img src='" + value + "' class='imagePath' style='width: 80px;height: 40px;'></a>"
            },
            cellStyle: function (value, row, index) {
                return _cellStyles(value, row, index);
            }
        },
        {
            title: '分数', field: 'score', align: 'center', valign: 'middle', width: 60,
            formatter: function (value, row, index) {
                if (value >= 0 && value != "") {
                    if (row.scoringStatus == 1) {
                        return parseFloat(row.scoreb).toFixed(2);
                    } else {
                        return parseFloat(value).toFixed(2);
                    }
                } else {
                    return 0.00;
                }
            },
            cellStyle: function (value, row, index) {
                return _cellStyles(value, row, index);
            }
        },
        {
            title: '总分', field: 'scoreTOTAL', align: 'center', valign: 'middle', width: 80,
            formatter: function (value, row, index) {
                if (value >= 0 && value != "") {
                    if (row.scoringStatus == 1) {
                        return parseFloat(row.scoreTOTALb).toFixed(2);
                    } else {
                        return parseFloat(value).toFixed(2);
                    }
                } else {
                    return 0.00;
                }
            },
            cellStyle: function (value, row, index) {
                return _cellStyles(value, row, index);
            }
        },
        {
            title: '图标', field: 'icon', align: 'center', valign: 'middle', width: 70,
            formatter: function (value, row, index) {
                if (row.scoringStatus == 1) {
                    if (row.scoreTOTALb >= row.standardScore) {
                        return "<span style='background: green;border-radius: 50%;width: 20px;height: 20px;display: inline-block;'></span>"
                    } else if (row.scoreTOTALb >= 60 && row.scoreTOTALb < row.standardScore) {
                        return "<span style='background: #FF7E00;border-radius: 50%;width: 20px;height: 20px;display: inline-block;'></span>"
                    } else if (row.scoreTOTALb >= 0 && row.scoreTOTALb < 60) {
                        return "<span style='background: red;border-radius: 50%;width: 20px;height: 20px;display: inline-block;'></span>"
                    }
                } else {
                    if (row.scoreTOTAL >= row.standardScore) {
                        return "<span style='background: green;border-radius: 50%;width: 20px;height: 20px;display: inline-block;'></span>"
                    } else if (row.scoreTOTAL >= 60 && row.scoreTOTAL < row.standardScore) {
                        return "<span style='background: #FF7E00;border-radius: 50%;width: 20px;height: 20px;display: inline-block;'></span>"
                    } else if (row.scoreTOTAL >= 0 && row.scoreTOTAL < 60) {
                        return "<span style='background: red;border-radius: 50%;width: 20px;height: 20px;display: inline-block;'></span>"
                    }
                }
            },
            cellStyle: function (value, row, index) {
                return _cellStyles(value, row, index);
            }
        },
        {
            title: '是否合格', field: 'isQualified', align: 'center', valign: 'middle', width: 80,
            formatter: function (value, row, index) {
                if (row.scoringStatus == 1) {
                    if (row.scoreTOTALb >= row.standardScore) {
                        return "<span>合格</span>"
                    } else if (row.scoreTOTALb > 0 && row.scoreTOTALb < row.standardScore) {
                        return "<span>不合格</span>"
                    } else {
                        return ""
                    }
                } else {
                    if (row.scoreTOTAL >= row.standardScore) {
                        return "<span>合格</span>"
                    } else if (row.scoreTOTAL > 0 && row.scoreTOTAL < row.standardScore) {
                        return "<span>不合格</span>"
                    } else {
                        return ""
                    }
                }
            },
            cellStyle: function (value, row, index) {
                return _cellStyles(value, row, index);
            }
        },
        {
            title: '操作', field: 'operation', align: 'center', valign: 'middle', width: 60,
            formatter: function (value, row, index) {
                if (row.iconName1 == "2") {
                    if (row.status == 1) {
                        return '<button title="详情" style="background: #ffffff;border: 1px solid #cccccc;padding: 1px 4px 0 5px;" onclick="QualityAssurances.detailsed(' + "'" + row.num + "'," + row.scoringStatus + ')" type="button" class="btn"><span class="glyphicon glyphicon-eye-open"></span></button>' +
                            '<button title="人工打分" style="background: #ffffff;border: 1px solid #cccccc;padding: 1px 4px 0 5px;" onclick="QualityAssurances.artificialScoring(' + "'" + row.num + "'" + ')" type="button" class="btn"><span class="glyphicon glyphicon-pencil"></span></button>'
                    } else {
                        return '<button title="人工打分" style="background: #ffffff;border: 1px solid #cccccc;padding: 1px 4px 0 5px;" onclick="QualityAssurances.artificialScoring(' + "'" + row.num + "'" + ')" type="button" class="btn"><span class="glyphicon glyphicon-pencil"></span></button>'
                    }
                } else {
                    return ""
                }
            },
            cellStyle: function (value, row, index) {
                return _cellStyles(value, row, index);
            }
        }
    ];
};

$(document).on("click", "th", function (field, value, row) {//点击表头
    var data = $('#QualityAssurancesOneTable').bootstrapTable('getData', true);
    if ($("#checkAll").prop("checked") == true) {
        $("#checkAll").prop('checked', false);
        $("input[name='checkImgNum']:checkbox").prop('checked', false);
        for (var i = 0; i < data.length; i++) {
            data[i].recordCheck = "";
        }
    } else if ($("#checkAll").prop("checked") == false) {
        $("#checkAll").prop('checked', true);
        $("input[name='checkImgNum']:checkbox").prop('checked', true);
        for (var i = 0; i < data.length; i++) {
            data[i].recordCheck = data[i].num;
        }
    }
});

mergeCells = function (data, fieldName, colspan, target) {
    var sort = new Array();
    var num = 1;
    for (var i = 0; i < data.length - 1; i++) {
        for (var prop in data[i]) {
            if (prop == fieldName) {
                if (data[i][prop] == data[i + 1][prop]) {
                    num++;
                    if (i == data.length - 2) {
                        sort.push(num)
                    }
                } else {
                    sort.push(num);
                    num = 1
                }
                break
            }
        }
    }
    var index = 0;
    for (var j = 0; j < sort.length; j++) {
        var count = sort[j];
        $(target).bootstrapTable('mergeCells', {
            index: index,
            field: fieldName,
            colspan: colspan,
            rowspan: count
        });
        index += count
    }
};

QualityAssurances.merge = function () {
    var data = $('#QualityAssurancesOneTable').bootstrapTable('getData', true);
    mergeCells(data, "addTime", 1, $('#QualityAssurancesOneTable'));
    mergeCells(data, "num", 1, $('#QualityAssurancesOneTable'));
};

QualityAssurances.detailsed = function (num,scoringStatus) {//点击表格展示详情
    if ($("#" + num).prop("checked") == true) {
        $("#" + num).prop('checked', false);
    } else if ($("#" + num).prop("checked") == false) {
        $("#" + num).prop('checked', true);
    }
    var index = layer.open({
        type: 2,
        title: '详情',
        area: ['80%', '90%'], //宽高
        fix: true, //不固定
        maxmin: true,
        content: Feng.ctxPath + '/qualityAssurances/score_detailsed/' + num +'/' + scoringStatus
    });
    this.layerIndex = index;
};

QualityAssurances.artificialScoring = function (num) {//点击表格展示人工打分
    if ($("#" + num).prop("checked") == true) {
        $("#" + num).prop('checked', false);
    } else if ($("#" + num).prop("checked") == false) {
        $("#" + num).prop('checked', true);
    }
    var index = layer.open({
        type: 2,
        title: '人工打分详情',
        area: ['80%', '90%'], //宽高
        fix: true, //不固定
        maxmin: true,
        content: Feng.ctxPath + '/qualityAssurances/artificial_scoring/' + num
    });
    this.layerIndex = index;
};

QualityAssurances.check = function () { // 检查是否选中
    var selected = $('#' + this.id).bootstrapTable('getSelections');
    if (selected.length == 0) {
        Feng.info("请先选中表格中的某一记录！");
        return false;
    } else {
        QualityAssurances.seItem = selected[0];
        return true;
    }
};

QualityAssurances.search = function () {//图片质量管理查询
    QualityAssurances.table.refresh({query: QualityAssurances.formParams()});
    QualityAssurances.total();
};

QualityAssurances.inquire = function () {//人数统计 + 表格刷新
    QualityAssurances.search();
    QualityAssurances.total();
};

QualityAssurances.getData = function () { // 片区筛选
    var params = {area: $("#area").val()};
    $.post(Feng.ctxPath + "/dept/getListByArea", params, function (data) {
        $('#arrivalStore').empty();
        for (var i = 0; i < data.length; i++) {
            $('#arrivalStore').append("<option value=" + data[i].simplename + ">" + data[i].simplename + "</option>");
        }
        QualityAssurances.search();
    }, "json");
};

QualityAssurances.total = function () {//人数统计
    var status = $("#status").val();  //合格状态
    var startUploadTime = $("#startUploadTime").val();  //开始回访时间
    var endUploadTime = $("#endUploadTime").val();  //结束回访时间
    var addName = $("#addName").val();  //开始创建时间
    var arrivalStore = $("#arrivalStore").val();  //结束创建时间
    $.ajax({
        type: "GET",
        url: Feng.ctxPath + "/qualityAssurances/total",
        data: {
            status: status,
            startUploadTime: startUploadTime,
            endUploadTime: endUploadTime,
            addName: addName,
            arrivalStore: arrivalStore
        },
        dataType: "json",
        success: function (data) {
            $("#total").html(data[0].countNum);//总人数
            $("#first").html(data[1].countNum);//待计划
            $("#two").html(data[2].countNum);//已完成
        }
    });
};

QualityAssurances.totalAllNumber = function (obj) {
    if (obj == "2") {
        $('#QualityAssurancesOneTable').bootstrapTable('hideColumn', 'score');
        $('#QualityAssurancesOneTable').bootstrapTable('hideColumn', 'icon');
        $('#QualityAssurancesOneTable').bootstrapTable('hideColumn', 'scoreTOTAL');
        $('#QualityAssurancesOneTable').bootstrapTable('hideColumn', 'isQualified');
        $('#QualityAssurancesOneTable').bootstrapTable('hideColumn', 'operation');
        $(".isQualified").hide();
        $("#intelligence").show();
        $("#intelligenceg").show();
    } else {
        $('#QualityAssurancesOneTable').bootstrapTable('showColumn', 'score');
        $('#QualityAssurancesOneTable').bootstrapTable('showColumn', 'icon');
        $('#QualityAssurancesOneTable').bootstrapTable('showColumn', 'scoreTOTAL');
        $('#QualityAssurancesOneTable').bootstrapTable('showColumn', 'isQualified');
        $('#QualityAssurancesOneTable').bootstrapTable('showColumn', 'operation');
        $(".isQualified").show();
        $("#intelligence").hide();
        $("#intelligenceg").hide();
    }
    $("#status").val(obj);
    QualityAssurances.inquire();
};

QualityAssurances.formParams = function () {//查询质量管理列表
    var queryData = {};
    queryData['startUploadTime'] = $("#startUploadTime").val();
    queryData['endUploadTime'] = $("#endUploadTime").val();
    queryData['addName'] = $("#addName").val();
    queryData['arrivalStore'] = $("#arrivalStore").val();
    queryData['status'] = $("#status").val();
    queryData['scoreTOTAL'] = $("#scoreTOTAL").val();
    return queryData;
};

QualityAssurances.resetSearch = function () {//重置
    $("#startUploadTime").val("");
    $("#endUploadTime").val("");
    $("#addName").val("");
    $("#arrivalStore").val("");
    $("#status").val("");
    $("#scoreTOTAL").val("");
    QualityAssurances.inquire();
};
QualityAssurances.intelligentScoring = function () {
    var ids = [];
    var data = $('#QualityAssurancesOneTable').bootstrapTable('getData', true);
    for (var i = 0; i < data.length; i++) {
        ids.push(data[i].num);
    }
    if (ids.length == 0) {
        alert("文件夹没有图片文件！");
        return false;
    }
    var content = '<div><span id="scoringNumber">0</span>/<span id="scoringTotal">'+unique(ids).length+'</span></div>';
    var userid = document.getElementById("userid").value;
    var abbreviation = document.getElementById("abbreviation").value;
    var websocket = null;
    if ('WebSocket' in window) {
        websocket = new WebSocket("ws://www.yiyatest.cn:8881/webSocketProgress/" + userid + '/' + abbreviation)
    } else {
        alert('Not support websocket！该浏览器不支持实时刷新，请使用谷歌浏览器急速模式！')
    }
    websocket.onerror = function () {
        setMessageInnerHTML("error")
    };
    websocket.onopen = function (event) {
        setMessageInnerHTML("open")
    };
    websocket.onmessage = function (event) {
        setMessageInnerHTML(event.data)
    };
    websocket.onclose = function () {
        setMessageInnerHTML("close")
    };
    window.onbeforeunload = function () {
        websocket.close()
    };
    function setMessageInnerHTML(innerHTML) {
        $("#scoringNumber").html(innerHTML)
    };
    function closeWebSocket() {
        websocket.close()
    };
    function send() {
        var message = document.getElementById('text').value;
        websocket.send(message)
    };
    var start_time = $("#startUploadTime").val();
    var end_time = $("#endUploadTime").val();
    var bd = new Date(start_time), be = new Date(end_time);
    var bd_time = bd.getTime(), be_time = be.getTime(), time_diff = be_time - bd_time;
    var d_arr = [];
    for (var i = 0; i <= time_diff; i += 86400000) {
        var ds = setDateTime(new Date(bd_time + i), 0);
        d_arr.push(ds);
    }
    if(d_arr.length==0){
        alert("请选择时间段评分！");
        return false;
    }
    var arrivalStore = $("#arrivalStore").val();
    if(arrivalStore==null || arrivalStore==""){
        alert("请选择门店！");
        return false;
    }
    var params = {
        arrivalStore: arrivalStore,
        area: $("#area").val(),
        time: d_arr,
        nums: unique(ids)
    };
    var loadIndex = '';
    $.ajax({
        url: Feng.ctxPath + "/intelligent/evaluation",
        dataType: "json",
        contentType: "application/json",
        data: JSON.stringify(params),
        type: "POST",
        beforeSend: function () {
            loadIndex = layer.load(1, {
                shade: [0.1, '#fff'],
                content: content,
                success: function (layero) {
                    layero.find('.layui-layer-content').css({
                        'padding-top': '39px',
                        'width': '60px'
                    });
                    $("#checkAll").prop('checked', false);
                    $("input[name='checkImgNum']:checkbox").prop('checked', false);
                    for (var i = 0; i < data.length; i++) {
                        data[i].recordCheck = "";
                    }
                }
            });
        },
        complete: function () {
            layer.close(loadIndex);
        },
        success: function (data) {
            Feng.success("评分成功！");
            window.QualityAssurances.search();
        }
    });
};

QualityAssurances.gouScoring = function () {
    var ids = [];
    var data = $('#QualityAssurancesOneTable').bootstrapTable('getData', true);
    for (var i = 0; i < data.length; i++) {
        if (data[i].recordCheck != null && data[i].recordCheck != "" && data[i].recordCheck != "undefined") {
            ids.push(data[i].recordCheck);
        }
    }
    if (ids.length == 0) {
        alert("请选择图片！");
        return false;
    }
    var content = '<div><span id="scoringNumber">0</span>/<span id="scoringTotal">'+unique(ids).length+'</span></div>';
    var userid = document.getElementById("userid").value;
    var abbreviation = document.getElementById("abbreviation").value;
    var websocket = null;
    if ('WebSocket' in window) {
        websocket = new WebSocket("ws://www.yiyatest.cn:8881/webSocketProgress/" + userid + '/' + abbreviation)
    } else {
        alert('Not support websocket！该浏览器不支持实时刷新，请使用谷歌浏览器急速模式！')
    }
    websocket.onerror = function () {
        setMessageInnerHTML("error")
    };
    websocket.onopen = function (event) {
        setMessageInnerHTML("open")
    };
    websocket.onmessage = function (event) {
        setMessageInnerHTML(event.data)
    };
    websocket.onclose = function () {
        setMessageInnerHTML("close")
    };
    window.onbeforeunload = function () {
        websocket.close()
    };

    function setMessageInnerHTML(innerHTML) {
        $("#scoringNumber").html(innerHTML)
    };

    function closeWebSocket() {
        websocket.close()
    };
    function send() {
        var message = document.getElementById('text').value;
        websocket.send(message)
    };
    var start_time = $("#startUploadTime").val();
    var end_time = $("#endUploadTime").val();
    var bd = new Date(start_time), be = new Date(end_time);
    var bd_time = bd.getTime(), be_time = be.getTime(), time_diff = be_time - bd_time;
    var d_arr = [];
    for (var i = 0; i <= time_diff; i += 86400000) {
        var ds = setDateTime(new Date(bd_time + i), 0);
        d_arr.push(ds);
    }
    if(d_arr.length==0){
        alert("请选择时间段评分！");
        return false;
    }
    var arrivalStore = $("#arrivalStore").val();
    if(arrivalStore==null || arrivalStore==""){
        alert("请选择门店！");
        return false;
    }
    var params = {
        arrivalStore: arrivalStore,
        area: $("#area").val(),
        time: d_arr,
        nums: unique(ids)
    };
    var loadIndex = '';
    $.ajax({
        url: Feng.ctxPath + "/intelligent/evaluation",
        dataType: "json",
        contentType: "application/json",
        data: JSON.stringify(params),
        type: "POST",
        beforeSend: function () {
            loadIndex = layer.load(1, {
                shade: [0.1, '#fff'],
                content: content,
                success: function (layero) {
                    layero.find('.layui-layer-content').css({
                        'padding-top': '39px',
                        'width': '60px'
                    });
                    $("#checkAll").prop('checked', false);
                    $("input[name='checkImgNum']:checkbox").prop('checked', false);
                    for (var i = 0; i < data.length; i++) {
                        data[i].recordCheck = "";
                    }
                }
            });
        },
        complete: function () {
            layer.close(loadIndex);
        },
        success: function (data) {
            Feng.success("评分成功！");
            window.QualityAssurances.search();
        }
    });
};

QualityAssurances.time = function () {//初始化赋值时间 + 请求数据
    $("#startUploadTime").val(setDateTime(new Date(), 0) + " " + "00:00:00");
    $("#endUploadTime").val(setDateTime(new Date(), 0) + " " + "23:59:59");
};

$(function () {
    var outpatientName = $('#outpatientName').val();
    var areaAbbreviation = $('#areaAbbreviation').val();
    $("#area option[value='" + areaAbbreviation + "']").attr("selected", "selected");
    $("#arrivalStore option[value='" + outpatientName + "']").attr("selected", "selected");
    var defaultColunms = QualityAssurances.initColumn();
    var table = new BSTable(QualityAssurances.id, "/qualityAssurances/list", defaultColunms);
    table.setPaginationType("server");
    table.setQueryParams(QualityAssurances.formParams());
    QualityAssurances.table = table.init();
    QualityAssurances.time();
    $("#totalAllNumber").addClass('actionClick').siblings().removeClass('actionClick');
    QualityAssurances.totalAllNumber("1");
    checkDate = function () {
        QualityAssurances.inquire();
    };
    $(document).on("load-success.bs.table", function () {
        QualityAssurances.merge()
    })
});

function unique(arr) {
    if (!Array.isArray(arr)) {
        console.log('type error!');
        return;
    }
    var array = [];
    for (var i = 0; i < arr.length; i++) {
        if (array.indexOf(arr[i]) === -1) {
            array.push(arr[i]);
        }
    }
    return array;
};